package com.srit.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.srit.core.bean.Page;
import com.srit.forecast.controller.vo.RoleVO;
import com.srit.system.bean.Role;
import com.srit.system.bean.Url;
import com.srit.system.dao.RoleDao;
import com.srit.system.dao.UrlDao;

@Controller
public class RoleController {
	@Autowired
	RoleDao roleDao;
	@Autowired
	UrlDao urlDao;
	@RequestMapping("/role-search")
	public String search(@ModelAttribute Page page) {
		roleDao.page(page);
		return "system/role";
	}
	@RequestMapping("/role-form")
	public String form(@ModelAttribute RoleVO roleVO,
			ModelMap modelMap) {
		List<Url> list = urlDao.listByAll();
		modelMap.addAttribute("urlList", list);
		return "system/role";
	}
	@RequestMapping("/role-edit")
	public String edit(@ModelAttribute RoleVO roleVO,ModelMap modelMap){
		List urlList = new ArrayList();
		Role role = roleDao.getById(roleVO.getId());
		String url[] = role.getUrl_id().split(",");
		for(int i = 0;i<url.length;i++){
			urlList.add(url[i]);
		}
		roleVO.setUrlList(urlList);
		roleVO.setName(role.getName());
		roleVO.setEnabled(role.getEnabled());
		List<Url> list = urlDao.listByAll();
		modelMap.addAttribute("urlList", list);
		return "system/role";
	}
	@RequestMapping("/role-saveOrUpdate")
	public String saveOrUpdate(RoleVO roleVO) {
		//roleVO role可合并，UrlList区别
		Role role = new Role();
		role.setId(roleVO.getId());
		role.setName(roleVO.getName());
		String str = roleVO.getUrlList().toString();
		str = str.replaceAll(" ", "");
		role.setUrl_id(str.substring(1, str.length()-1) );
		role.setEnabled(roleVO.getEnabled());
		if (role.getId() != null && role.getId() != 0) {
			roleDao.update(role);
		} else {
			roleDao.save(role);
		}
		return "forward:/role-search";
	}
}
